﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Syufy.BINLookup.Web.Interfaces;

namespace Syufy.BINLookup.Web.Models
{
    /// <summary>
    /// Unit of work class for database repositories.
    /// </summary>
    public class UnitOfWork<TContext> : IUnitOfWork where TContext : IDbContext, new()
    {
        private readonly IDbContext _context;
        private Dictionary<Type, object> _repositories;
        private bool _disposed;

        /// <summary>
        /// Unit of work constructor.
        /// </summary>
        public UnitOfWork()
        {
            _context = new TContext();
            _repositories = new Dictionary<Type, object>();
            _disposed = false;
        }

        /// <summary>
        /// Get unit of work for entity.
        /// </summary>
        public IGenericRepository<TEntity> GetRepository<TEntity>() where TEntity : class
        {
            if (_repositories.Keys.Contains(typeof(TEntity)))
            {
                return _repositories[typeof(TEntity)] as IGenericRepository<TEntity>;
            }

            var repository = new GenericRepository<TEntity>(_context);
            _repositories.Add(typeof(TEntity), repository);

            return repository;
        }

        /// <summary>
        /// Save database context.
        /// </summary>
        public void Save()
        {
            _context.SaveChanges();
        }

        /// <summary>
        /// Save database context (async).
        /// </summary>
        public async Task SaveAsync()
        {
            await _context.SaveChangesAsync();
        }

        /// <summary>
        /// IDisposable override.
        /// </summary>
        /// <param name="disposing"></param>
        protected virtual void Dispose(bool disposing)
        {
            if (!_disposed)
            {
                if (disposing)
                {
                    _context.Dispose();
                }
            }
            _disposed = true;
        }

        /// <summary>
        /// Dispose context.
        /// </summary>
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
    }
}